import { ElMessage } from 'element-plus'
import router from './index'
import { useUserStore, usePermissionStoreWithOut } from '@/store'
import { useNProgress } from '@/hooks/useNProgress'
import { useDynamicTitle } from '@/hooks/useDynamicTitle'

const { start, done } = useNProgress()

const whiteList = ['/login']

const permissionStore = usePermissionStoreWithOut()

router.beforeEach(async (to, from, next) => {
  start()
  const userStore = useUserStore()
  if (userStore.token) {
    if (to.path === '/login') {
      next({ path: '/' })
      done()
    } else {
      if (permissionStore.addRouters.length === 0) {
        try {
          await userStore.getUserInfo()

          const accessRoutes = await permissionStore.generateRoutes()
          // 根据roles权限生成可访问的路由表
          accessRoutes.forEach(item => {
            router.addRoute(item) // 动态添加可访问路由表
          })
          const redirectPath = from.query.redirect || to.path
          const redirect = decodeURIComponent(redirectPath)
          const nextData = to.path === redirect ? { ...to, replace: true } : { path: redirect }
          next(nextData)
        } catch (err) {
          userStore.logout().then(() => {
            ElMessage.error(err)
            next({ path: '/login' })
          })
        }
      } else {
        next()
      }
    }
  } else {
    // 没有token
    if (whiteList.includes(to.path)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next({ path: '/login', query: { redirect: to.fullPath } }) // 否则全部重定向到登录页
      done()
    }
  }
})

router.afterEach((to) => {
  useDynamicTitle(to?.meta?.title)
  done()
})
